# -*- coding: utf-8 -*-
import BeautifulSoup
import re
import os
import copy
import sys

def genPHPCode(inFile, outFile):
        #read tpl file and BeautifulSoup it
        file = open(inFile, "r")
        tmpFileContent = file.read()
        file.close()
        #replace regions
        soupTmp = BeautifulSoup.BeautifulSoup(tmpFileContent)
        #regions
        regionSoups = _getRegionSoups(soupTmp)
        #print regionSoups
        for regionSoup in regionSoups:
            attrs = regionSoup._getAttrMap()
            #print attrs
            if attrs.has_key("display"):
                del(regionSoup["display"])
                firstNode = True
                if len(regionSoup.contents) <= 0:
                    tmpContent = re.sub("(<.*?>)[\r\n]*?(<\/.*?>)", r"\1<?php XPFace::getRegion('"+ regionSoup["id"] +r"');>\2", regionSoup.prettify())
                    regionSoup.replaceWith(tmpContent)
                    #print tmpContent
                for content in regionSoup.contents:
                    if firstNode == True:
                        content.replaceWith("<?php XPFace::getRegion('"+ regionSoup["id"] +"');>")
                        firstNode = False
                    else:
                        content.replaceWith("")
            #if attrs.has_key("display"):
            else:
                regionSoup.replaceWith("<?php XPFace::getRegion('"+ regionSoup["id"] +"');>")
        
        soup = BeautifulSoup.BeautifulSoup(soupTmp.prettify())
        
        #parse
        parseIf(soup)
        parseForeach(soup)
        
        
        #print soup.prettify()
        outFileContent = parseVar(soup.prettify())
        #print outFileContent
        #write to file
        file2 = open(outFile, "w")
        file2.write(outFileContent)
        file2.close()
        
def parseVar(content):
    #replace the {$xxxx} tags
    content = re.sub("\{\$(.*?)\|html\}", r"<?php echo htmlspecialchars($\1);?>", content)
    content = re.sub("\{\$(.*?)\|js\}", r"<?php echo addslashes($\1);?>", content)
    content = re.sub("\{\$(.*?)\}", r"<?php echo $\1?>", content)
    
    content = re.sub("execute=\"(.*?)\|html\"", r"<?php echo htmlspecialchars(\1);?>", content)
    content = re.sub("execute=\"(.*?)\|js\"", r"<?php echo addslashes(\1);?>", content)
    content = re.sub("execute=\"(.*?)\"", r"<?php echo \1?>", content)
    
    #textarea
    content = re.sub("(<textarea\s.*?>)[\r\n\s]*(.*?)[\r\n\s]*</textarea>", r"\1\2</textarea>", content)
    
    #parse .
    content = re.sub("\$([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)", r"$\1->\2->\3->\4", content)
    content = re.sub("\$([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)", r"$\1->\2->\3", content)
    content = re.sub("\$([_a-zA-Z]\w*?)\.([_a-zA-Z]\w*?)", r"$\1->\2", content)
    
    #parse .$xxx
    content = re.sub("\$([_a-zA-Z]\w*)\.(\$[\w\->]*)", r"$\1->{\2}", content)
    
    
    
    return content


def parseIf(soup):
    #get if soups
    ifSoups = soup.findAll(attrs={'if' : re.compile(".*")})
    #print "\n1111111111111111111111111\n"
    for ifSoup in reversed(ifSoups):
        #if have foreach parse it
        parseForeach(ifSoup)
        
        #to php code
        #print "\n1111111111111111111111111\n"
        ifContent = re.sub("\.", r"->", ifSoup["if"])
        del(ifSoup["if"])
        ifCode = u"<?php if (" + ifContent + "):?>" + unicode(ifSoup.prettify(),"utf-8") + u"<?php endif;?>"
        ifSoup.replaceWith(ifCode)
        

def parseForeach(soup):
    #get foreach soups
    foreachSoups = soup.findAll(attrs={'foreach' : re.compile(".*")})
    #print soup
    #print 1111111111111111;
    for foreachSoup in reversed(foreachSoups):
        #print foreachSoup
        #print 1111111111111111;
        #to php code
        foreachContent = re.sub("\.", r"->", foreachSoup["foreach"])
        foreachContent = re.sub("as\s+", r"as $key=>", foreachContent)
        foreachDataVar = re.sub("\s+as\s+(.*)", r"", foreachContent)
        del(foreachSoup["foreach"])
        indexVarName = foreachSoup.name + r"Num"
        foreachCode = u"<?php if (is_array(" + foreachDataVar + ") > 0): $" + indexVarName + "=0; foreach (" + foreachContent + "):?>"
        print indexVarName
        #break
        topLoopContent = u"";
        bottomLoopContent = u"";
        for child in foreachSoup.contents:
            if child.__class__ == BeautifulSoup.Tag:
                attrs = child._getAttrMap()
                if attrs.has_key("noloop"):
                    if attrs.get("noloop") != "bottom":
                        del(child["noloop"])
                        topLoopContent = topLoopContent + unicode(child.__str__(),"utf-8")
                    else:
                        del(child["noloop"])
                        bottomLoopContent = bottomLoopContent + unicode(child.__str__(),"utf-8")
                    child.replaceWith("")
                    continue
            foreachCode = foreachCode + unicode(child.__str__(),"utf-8")
            #print foreachCode
            child.replaceWith("")
        foreachCode += u"<?php $" + indexVarName + u"++; endforeach;?>" + u"<?php endif;?>"
        
        foreachCode = topLoopContent + foreachCode + bottomLoopContent
        #print foreachCode
        
        foreachSoup.contents[0].replaceWith(foreachCode)
        #foreachSoup.replaceWith("")


def _getRegionSoups(tmpSoup):
    return tmpSoup.findAll("div", {"class" : re.compile("^region.*")})

if __name__ == '__main__':
    #print sys.argv
    genPHPCode(sys.argv[1], sys.argv[2])
